package com.yuedou.jylt.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import com.yuedou.jylt.MainActivity;
import com.yuedou.jylt.R;
import com.yuedou.jylt.constant.MApplication;
import com.yuedou.jylt.sharedpref.SharedPrefConstant;
import com.yuedou.jylt.utils.StatusBarUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

public class SplashActivity extends Activity{
	private static final int GO_HOME = 1000;
	private static final int GO_SETTING = 1001;
	private static final int GO_ADBANNER = 1002;
	// 延迟3秒
	private static final long SPLASH_DELAY_MILLIS = 1000;
	private static final String SHAREDPREFERENCES_NAME = "cft_first_pref";

	private String deviceSn = "";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		StatusBarUtils.setWindowStatusBarColor(this);
		init();

		String s = Environment.getExternalStorageDirectory().getAbsolutePath()
				+ File.separator + "snda" + File.separator + "log" ;
		Log.i("日志路径",s);

		//判断是否为Android6.0系统版本，如果是，动态开启权限
		if (Build.VERSION.SDK_INT >= 23) {
			initPermission();
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		System.out.println("执行 start");
	}

	/**
	 *  初始化方法
	 */
	private void init() {
		// 读取SharedPreferences中需要的数据
		// 使用SharedPreferences来记录程序的使用次数
		SharedPreferences preferences = getSharedPreferences(SHAREDPREFERENCES_NAME, MODE_PRIVATE);

		// 取得相应的值，如果没有该值，说明还未写入，用true作为默认值
		boolean isFirstIn = preferences.getBoolean("isFirstIn", true);
		// 判断程序与第几次运行，如果是第一次运行则跳转到引导界面，否则跳转到主界面
		if (isFirstIn) {
			System.out.println("========首次启动============");
			mHandler.sendEmptyMessageDelayed(GO_ADBANNER, SPLASH_DELAY_MILLIS);
			MApplication.mSharedPref.putSharePrefInteger(SharedPrefConstant.MORE_NRECORD_COUNT, 30);
			setGuided();
		} else {
			// 使用Handler的postDelayed方法，3秒后执行跳转到MainActivity
			this.deviceSn = MApplication.mSharedPref.getSharePrefString(SharedPrefConstant.DEVICE_SN);
			System.out.println("============ 设备编号 " + this.deviceSn + "===========");
			if(TextUtils.isEmpty(this.deviceSn)){//已经初始化过了
				//MainActivity
				System.out.println("设置界面");
				mHandler.sendEmptyMessageDelayed(GO_ADBANNER, SPLASH_DELAY_MILLIS);
			}else{
				//PlayVideoActivity
				System.out.println("广告界面");
				mHandler.sendEmptyMessageDelayed(GO_ADBANNER, SPLASH_DELAY_MILLIS);
			}
		}
	}

	/**
	 *
	 * method desc：设置已经引导过了，下次启动不用再次引导
	 */
	private void setGuided() {
		SharedPreferences preferences = getSharedPreferences(SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = preferences.edit();
		// 存入数据
		editor.putBoolean("isFirstIn", false);
		// 提交修改
		editor.commit();
	}

	/**
	 * Handler:跳转到不同界面
	 */
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case GO_HOME:
					goGuide();
					break;
				case GO_SETTING:
					goAdBanner();
					break;
				case GO_ADBANNER:
					goAdBanner();
					break;
			}
			super.handleMessage(msg);
		}
	};


	private void goGuide(){
		Intent intent = new Intent(this,MainActivity.class);
		startActivity(intent);
	}

	private void goSetting(){
		Intent intent = new Intent(this,MainActivity.class);
		startActivity(intent);
	}
	
	private void goAdBanner(){
		Intent intent = new Intent(this, MainActivity.class);
		startActivity(intent);
	}

	String[] permissions = new String[]{
			Manifest.permission.READ_EXTERNAL_STORAGE,
			Manifest.permission.WRITE_EXTERNAL_STORAGE,
			Manifest.permission.ACCESS_COARSE_LOCATION,
			Manifest.permission.ACCESS_WIFI_STATE ,
			Manifest.permission.SYSTEM_ALERT_WINDOW ,
			Manifest.permission.CAMERA ,
			Manifest.permission.READ_PHONE_STATE,
			Manifest.permission.RECORD_AUDIO};

	private final int mRequestCode = 100;

	List<String> mPermissionList = new ArrayList<>();

	@Override
	protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {

		}
	}

	private void initPermission() {
		mPermissionList.clear();
		for (int i = 0; i < permissions.length; i++) {
			if (ContextCompat.checkSelfPermission(this, permissions[i]) != PERMISSION_GRANTED) {
				mPermissionList.add(permissions[i]);
			}
		}
		if (mPermissionList.size() > 0) {
			ActivityCompat.requestPermissions(this, permissions, mRequestCode);
		}
	}

	/**
	 * 显示提示信息,与verifyShouldShowRequestPermissions(String[] permissions)搭配使用，提醒用户需要授权，并打开应用详细设置页面
	 *
	 * @since 2.5.0
	 */
	protected void showMissingPermissionDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("提示");
		builder.setMessage("当前应用缺少必要权限。\n请点击\"设置\"-\"权限\"打开所需权限。");
//        // 拒绝, 退出应用
//        builder.setNegativeButton(R.string.cancel,
//                listener
//        );
		builder.setPositiveButton(R.string.setting,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						startAppSettings();
					}
				});
		builder.setCancelable(false);
		builder.show();
	}

	/**
	 * 启动应用的设置
	 *
	 * @since 2.5.0
	 */
	private void startAppSettings() {
		Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
		intent.setData(Uri.parse("package:" + getPackageName()));
		startActivity(intent);
	}

	private boolean verifyPermissions(int[] grantResults) {
		for (int result : grantResults) {
			if (result != PERMISSION_GRANTED) {
				return false;
			}
		}
		return true;
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		boolean grandResult = verifyPermissions(grantResults);
		if (!grandResult) {
			showMissingPermissionDialog();
		}
	}
}
